/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.marcelo.agro.totales.gui;

import java.awt.BorderLayout;
import java.util.Collection;
import java.util.List;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.marcelo.agro.core.DynamicLookup;
import org.marcelo.agro.core.api.ITotales;
import org.marcelo.agro.entidades.Campanas;
import org.marcelo.agro.entidades.Lotes;
import org.marcelo.agro.entidades.LotesPorCampana;
import org.marcelo.agro.entidades.TipoActividad;
import org.marcelo.agro.entidades.noadministrados.Estadisticas;
import org.marcelo.agro.entidades.eventos.ActividadesEvent;
import org.marcelo.agro.totales.util.TotalesUtil;
import org.marcelo.comun.notificaciones.Notificaciones;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.util.Utilities;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.marcelo.gps.gui//ChartTotales//EN",
autostore = false)
@TopComponent.Description(preferredID = "ChartTotalesTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "org.marcelo.totales.gui.ChartTotalesTopComponent")
@ActionReference(path = "Menu/Reportes" /*
 * , position = 333
 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_ChartTotalesAction",
preferredID = "ChartTotalesTopComponent")
@Messages({
    "CTL_ChartTotalesAction=ChartTotales",
    "CTL_ChartTotalesTopComponent=ChartTotales Window",
    "HINT_ChartTotalesTopComponent=This is a ChartTotales window"
})
public final class ChartTotalesTopComponent extends TopComponent implements LookupListener{
    
    //Campos para FX
    
    private PieChart pieChart;
    private Scene scene;
            
    
    private Lookup.Result<Campanas> resultCampanas;
    private Lookup.Result<LotesPorCampana> resultLCP;
    private Lookup.Result<ActividadesEvent> resultEvent;
    
    private ITotales it = Lookup.getDefault().lookup(ITotales.class);
    
    final static String VENTANA_LOOKUP= "VistaCampanhasTopComponent";
    final static String TITULO_CHART_CAMPANIA = "Total Gasto en Campaña: ";
    final static String TITULO_CHART_LOTE = "Total Gasto en Lote: ";
    private JFXPanel chartFxPanel;
    private int PANEL_WIDTH_INT = 500, PANEL_HEIGHT_INT= 500;
    private int LABEL_LINE_LENGTH = 10;
    
    private void initChart() {
        
        ObservableList data = FXCollections.observableArrayList();
        //Caption para mostrar datos
        final Label caption = new Label("");
        caption.setTextFill(Color.DARKORANGE);
        caption.setStyle("-fx-font: 24 arial;");
        //Solo para probar un grafico
        List<Estadisticas<Campanas>> eaList =   it.getTotales();
        
        for (Estadisticas<Campanas> ec : eaList){
            data.add(
                        new PieChart.Data(ec.getCampoAgrupamiento().getNombre(), ec.getSum().doubleValue())
//                        .getNode()
//                        .addEventHandler(javafx.scene.input.MouseEvent.MOUSE_PRESSED , 
//                            new EventHandler<javafx.scene.input.MouseEvent>(){
//                                @Override public void handle(javafx.scene.input.MouseEvent e) {
//                                    caption.setTranslateX(e.getSceneX());
//                                    caption.setTranslateY(e.getSceneY());
//                                    caption.setText(String.valueOf(ec.getSum()) + "%");
//                                }
//                            }
//                        )
                    );
        }
        
        pieChart = new PieChart((data)); 
        
        //Bucle para agregar listeners
        
//        for (final PieChart.Data  datos : pieChart.getData()){
//                datos.getNode()
//                    .addEventHandler(javafx.scene.input.MouseEvent.MOUSE_PRESSED , 
//                    new EventHandler<javafx.scene.input.MouseEvent>(){
//                        @Override public void handle(javafx.scene.input.MouseEvent e) {
//                            caption.setTranslateX(e.getSceneX());
//                            caption.setTranslateY(e.getSceneY());
//                            caption.setText(String.valueOf(datos.getPieValue()) + "%");
//                        }
//                    });
//        }
        
        pieChart.setId("chartTotales");
        pieChart.setTitle(TITULO_CHART_CAMPANIA);
        pieChart.setLabelLineLength(LABEL_LINE_LENGTH);
//        pieChart.setLegendSide(Side.LEFT);
        
        
        
        chartFxPanel = new JFXPanel();
//        chartFxPanel.setPreferredSize(new Dimension(PANEL_WIDTH_INT, PANEL_HEIGHT_INT));
        
        
        JPanel jpanel = new JPanel(new BorderLayout());
//        jpanel.setPreferredSize(new Dimension(PANEL_WIDTH_INT, PANEL_HEIGHT_INT));;
        jpanel.add(chartFxPanel, BorderLayout.CENTER);
        
        add(jpanel,BorderLayout.CENTER);
        //Para que no se borre al salir
        Platform.setImplicitExit(false);
        Platform.runLater(new Runnable() {

            @Override
            public void run() {
                scene = new Scene(pieChart);
//                ((Group) scene.getRoot()).getChildren().add(pieChart);
                chartFxPanel.setScene(scene);
            }
        });
    }

    public ChartTotalesTopComponent() {
        initComponents();
        setName(Bundle.CTL_ChartTotalesTopComponent());
        setToolTipText(Bundle.HINT_ChartTotalesTopComponent());
        setLayout(new BorderLayout());
        initChart();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
        resultCampanas = WindowManager.getDefault()
                .findTopComponent(VENTANA_LOOKUP).getLookup()
                .lookupResult(Campanas.class);
        resultLCP = WindowManager.getDefault()
                .findTopComponent(VENTANA_LOOKUP).getLookup()
                .lookupResult(LotesPorCampana.class);
        resultEvent = DynamicLookup.getDefault().lookupResult(ActividadesEvent.class);
//        resultCampanas = Utilities.actionsGlobalContext()
//                .lookupResult(Campanas.class);
//        resultLCP = Utilities.actionsGlobalContext()
//                .lookupResult(LotesPorCampana.class);
        
        resultCampanas.addLookupListener(this);
        resultLCP.addLookupListener(this);
        resultEvent.addLookupListener(this);
        //Para actualizar la vista de acuerdo al contexto
        resultChanged(new LookupEvent(resultCampanas));
        resultChanged(new LookupEvent(resultLCP));
        resultChanged(new LookupEvent(resultEvent));
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
         // TODO add custom code on component closing
        resultCampanas.removeLookupListener(this);
        resultLCP.removeLookupListener(this);
        resultEvent.removeLookupListener(this);
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    public void resultChanged(LookupEvent le) {
        
        final LookupEvent le1 = le;
        
//        SwingUtilities.invokeLater(new Runnable() {
//          @Override
//          public  void run() {
          
                Lookup.Result r = (Lookup.Result) le.getSource();
        
                Collection<? extends LotesPorCampana> lotesPorCampanas;
                Collection<? extends Campanas> listCampanias;
                List<Estadisticas<TipoActividad> > estadisticasLote = null;
                List<Estadisticas<Lotes> > estadisticasCampania = null;

                 if (r.equals(resultLCP)){
                    lotesPorCampanas = r.allInstances();
                    estadisticasLote =TotalesUtil.getEstadisticasLote(lotesPorCampanas);
                }
                else if (r.equals(resultCampanas)){
                    listCampanias = r.allInstances();
                    estadisticasCampania = TotalesUtil.getEstadisticasCampania(listCampanias);
                } 
                else if (r.equals(resultEvent)) {
                    Collection<? extends ActividadesEvent> nodeEvents = r.allInstances();

                    for (ActividadesEvent ne : nodeEvents) {
//                        if ( ne.getTipo().equals(NodeEvent.TIPOS_EVENTO.NEW) && ( ne instanceof NodeRefreshEvent || ne instanceof NodeNewEvent ) ) {
                            //Aca actualizare los datos
                            Campanas c = Utilities.actionsGlobalContext().lookup(Campanas.class);
                            if (c != null) {
        //                        cargar datos para campania
                                estadisticasCampania = it.getTotales(c);
                            }
                            else {
                                LotesPorCampana lpc = Utilities.actionsGlobalContext().lookup(LotesPorCampana.class);
                                if (lpc != null) {
        //                        cargar datos para lpc
                                    estadisticasLote = it.getTotales(lpc.getCampanas(), lpc.getLotes());
                                }
                                
                            }
//                        }
                    }

                }

                updateChart(estadisticasLote, estadisticasCampania);

//          }
//        });
        
        
        
        
    }
    
    /**
     * Para que sea mas facil las futuras modificaciones
     * @param name
     * @param value 
     */
    
    
    /**
     * Metodo para Ejecutar las modificaciones en el chart desde un nuevo thread
     */
    
    private void updateChart(final List<Estadisticas<TipoActividad> > el, final List<Estadisticas<Lotes>> ec) {
        Platform.runLater(new Runnable() {

            @Override
            public void run() {
                if (el != null ){
                    pieChart.getData().clear();
                    for (Estadisticas<TipoActividad> est : el ) {
                        addDatosToChart(est.getCampoAgrupamiento().getNombre(),  est.getSum().doubleValue());
                    }
//                    if (!datosPie.containsAll(data))
                        pieChart.setTitle(TITULO_CHART_LOTE);
                }
                else if (ec != null){
                    pieChart.getData().clear();
                    for (Estadisticas<Lotes> est : ec ) {
                        addDatosToChart(est.getCampoAgrupamiento().getNombre(),  est.getSum().doubleValue());
                    }
//                    if (!datosPie.containsAll(data))
//                        pieChart.setData(data);
                        pieChart.setTitle(TITULO_CHART_CAMPANIA);
                }
            }
            
            private void addDatosToChart(String name, Double value){
                pieChart.getData().add( new PieChart.Data(name, value) );
        
            }
        });
    }
    
}
